package cn.cvs.web;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.util.Constants;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色信息
 */
@Controller
public class SysRoleController {

    @Resource
    SysRoleService sysRoleService;

    /**
     *角色信息
     */
    @RequestMapping("/sys/role/list")
    public String roleList(Model model){
        List<SysRole> sysRoles = sysRoleService.queryAll();
        model.addAttribute("roleList",sysRoles);
        return "sysRole/list";
    }

    /**
     * 跳转修改角色页面
     */
    @RequestMapping("/sys/role/toUpdate/{rid}")
    public String toRoleUpdate(@PathVariable("rid") Integer rid, Model model){
        //根据id查找用户
        SysRole sysRole = sysRoleService.queryById(rid);
        model.addAttribute("sysRole",sysRole);
        return "sysRole/update";
    }

    /**
     * 修改角色信息页面
     */
    @PostMapping("/sys/role/update")
    public String roleUpdate(@RequestParam(value = "id",required = false) Integer id,
                             @RequestParam(value = "roleName",required = false) String roleName, HttpSession session){
        SysRole sysRole=new SysRole();
        //判断用户是否登录
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (sysUser==null) {
            return "redirect:/toLogin";
        }
        sysRole.setId(id);
        sysRole.setRoleName(roleName);
        //修改人id
        sysRole.setUpdatedUserId(sysUser.getId());
        //修改时间
        sysRole.setUpdatedTime(new Date());
        //修改角色信息
        System.out.println("角色信息:"+sysRole);
        int update = sysRoleService.modifyRole(sysRole);//未执行
        if (update>0) {
            return "redirect:/sys/role/list";
        }else{
            throw new RuntimeException("修改角色信息失败,请稍后再试");
        }
    }

    /**
     * 异步删除角色信息
     */
    @DeleteMapping("/sys/role/del/{rid}")
    public Object delRole(@PathVariable("rid") Integer rid, HttpSession session){
        Map<String,Object> resultMap=new HashMap<String,Object>();
        try {
            //判断用户是否登录
            SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
            if (sysUser==null) {
                resultMap.put("delResult","noLogin");
                resultMap.put("msg","对不起,请登录后操作");
                return JSON.toJSONString(resultMap);
            }
            //是否为管理员
            if (sysUser.getRoleId()!=1) {
                resultMap.put("delResult","notadmin");
                resultMap.put("msg","对不起,非管理员不能删除角色信息");
                return JSON.toJSONString(resultMap);
            }
            //参数
            if (rid==null) {
                resultMap.put("delResult","error");
                resultMap.put("msg","参数错误");
                return JSON.toJSONString(resultMap);
            }
            //根据id查询当前角色是否存在
            SysRole sysRole = sysRoleService.queryById(rid);
            if (sysRole==null) {
                resultMap.put("delResult","notexist");
                return JSON.toJSONString(resultMap);
            }else{
                //查询是否有用户引用他
                int count = sysRoleService.queryByRoleIdAndUserCount(rid);
                System.out.println("用户的关联数量"+count);
                if (count>0) {
                    resultMap.put("delResult","false");
                }else{
                    //删除角色
                    int delete = sysRoleService.deleteRole(rid);
                    if (delete>0) {
                        resultMap.put("delResult","true");
                    }else{
                        resultMap.put("delResult","false");
                    }
                }
                return JSON.toJSONString(resultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("delResult","error");
            resultMap.put("msg","系统繁忙,请稍后再试");
            return JSON.toJSONString(resultMap);
        }
    }

    /**
     * 跳转添加角色信息
     */
    @RequestMapping("/sys/role/toAdd")
    public String toRoleAdd(){
       return "sysRole/add";
    }

    /**
     * 异步请求查看用户编码是否为唯一
     */
    @ResponseBody
    @GetMapping("/sys/role/codeExist")
    public Object codeExist(String code){
        Map<String,Object> resultMap=new HashMap<String,Object>();
        try {
            int byCode = sysRoleService.queryByCode(code);
            if (byCode>0) {
                resultMap.put("exist","1");
            }else{
                resultMap.put("exist","0");
            }
            return JSON.toJSONString(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("exist","-1");
            resultMap.put("msg","哎呀,忙不过来了,待会再来吧");
            return JSON.toJSONString(resultMap);
        }
    }

    /**
     * 添加角色
     */
    @PostMapping("/sys/role/add")
    public String roleAdd(SysRole sysRole, HttpSession session){
        //判断用户是否登录
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (sysUser==null) {
            return "redirect:/toLogin";
        }
        //只有管理员才能添加角色
        if (sysUser.getRoleId()!=1) {
            throw new RuntimeException("非管理员不能添加角色信息");
        }
        sysRole.setCreatedUserId(sysUser.getId());
        sysRole.setCreatedTime(new Date());
        int insert = sysRoleService.insertRole(sysRole);
        if (insert>0) {
            return "redirect:/sys/role/list";
        }else{
            throw new RuntimeException("添加角色信息,请稍后再试");
        }
    }

}
